package com.itsu.compoment.socket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author 苏犇
 * @create time 2019/12/4 21:15
 */
@Slf4j
public class MyWebSocketHandler extends TextWebSocketHandler {

    private static final ConcurrentMap<String, WebSocketSession> USERS;

    private static final String WEBSOCKT_USER = "userId";

    static {
        USERS = new ConcurrentHashMap<>();
    }

    public static Set<String> getLoginUsers() {
        return USERS.keySet();
    }


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("新的客服端连接 。。。 session id:{}", session.getId());
        String userId = (String) session.getAttributes().get(WEBSOCKT_USER);
        USERS.putIfAbsent(userId, session);
        log.info("当前在线人数为：{}", USERS.size());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String msgStr = message.getPayload();
        JSONObject json = JSON.parseObject(msgStr);
        Message msg = json.toJavaObject(Message.class);
        String userId = msg.getToUserId();
        if (StringUtils.isNoneEmpty(userId)) {
            this.sendMessageToUser(userId, message);
        } else
            this.sendMessageToUsers(message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("发生异常", exception);
        if (session.isOpen()) {
            session.close();
        }
        WebSocketSession execSession = USERS.remove(session.getId());
        log.error("异常产生的session id：{}", execSession.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("有socket连接关闭，session id:{}", session.getId());
        log.info("reason: {}", status.getReason());
        String userId = (String) session.getAttributes().get(WEBSOCKT_USER);
        USERS.remove(userId);
        log.info("剩余在线人数为：{}", USERS.size());

    }

    public static synchronized void sendMessageToUser(String userId, TextMessage message) {

        USERS.forEach((key, value) -> {
            if (key.equals(userId)) {
                try {
                    value.sendMessage(message);
                } catch (IOException e) {
                    log.error("exception happened on send socket message");
                }
            }
        });
    }

    public static synchronized void sendMessageToUsers(TextMessage message) {
        USERS.forEach((key, value) -> {
            try {
                value.sendMessage(message);
            } catch (IOException e) {
                log.error("exception happened on send socket message");
            }
        });
    }
}
